/*
 * AllChartEntry.java
 *
 * Created on June 27, 2006, 2:09 PM
 *
 */

package galronnlp.pcfg.parser;

import galronnlp.pcfg.parser.EntryTriple;
import galronnlp.util.Tuple;
import galronnlp.util.SortedLinkedList;
import java.util.Iterator;

/**
 * A class  that stores all the items offered in a list, keeping
 * track of the total probability. These items are sorted in a
 * <code>SortedLinkedList</code> of <code>EntryTriple</code>s, sorted
 * in order of probabilities; Note that the <code>EntryTriple</code>s have
 * the following format: (double probability, int count, Edge edge).
 * <p>
 * This is based on the Chart Entries as defined in Chris Brew's python
 * Statistical CKY parser
 *
 * @author Daniel A. Galron
 */
public class AllChartEntry implements ChartEntry {
    
    boolean DEBUG = false;
    
    double probability = 0.0;
    int count = 0;
    SortedLinkedList<EntryTriple> items = new SortedLinkedList<EntryTriple>();    
    
    /** Creates a new instance of AllChartEntry */
    public AllChartEntry() {
    }
    
    public AllChartEntry(boolean debug) {
        DEBUG = debug;
    }

    /**
     * Add a new entry to the current chart. This does three things:
     * <p>
     * 1) It increments the count in this chart entry
     * 2) It adds the probability in this chart entry to the probability in the
     * <code>EntryTriple</code> being added to the chart entry
     * 3) It puts the new entry in sorted order in the <code>SortedLinkedList</code>
     */
    public void add(EntryTriple entry) {
        if(DEBUG)
            System.err.println("addAllChartEntry " + entry);
        double entryProb  = ((Double)entry.get(0)).doubleValue();
        int entryCount = ((Integer)entry.get(1)).intValue();
        this.probability = Math.max(entryProb, this.probability);
        //this.probability += entryProb;
        this.count += entryCount;
        this.items.insort(entry);
    }
    
    public int count() {
        return count;
    }
    
    public double probability() {
        return probability;
    }
    
    public SortedLinkedList<EntryTriple> items() {
        return items;
    }
    
    public String toString() {
        String ret = "(" + this.probability + ", " + this.count + ", {";
        for(Iterator<EntryTriple> i = items.iterator(); i.hasNext(); ) {
            ret += i.next() + ", ";
        }
        ret += "})\n";
        return ret;
    }
    
}
